<?php

require_once PATH_BASE.'lib/fpdf/fpdf.php';
require_once PATH_BASE.'application/connectionDB.php';
require_once PATH_BASE.'controller/supercontroller.php';

class template {
	
	private static $templateInstance;
	
	var $connection;
	var $error = array();
	var $info = array();
	
	var $bodyPage =LOGIN_PAGE;
	
	static function getInstance()
	{
		if(!isset(self::$templateInstance))
		{
			$c = __CLASS__;
			self::$templateInstance = new template;
		}
		return self::$templateInstance;
	}
	
	private function __construct()
	{
		$this->connection = connectionDB::getInstance();
		
	}
	
	
 	// Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }


    public function buildHead()
    {
    	include_once PATH_BASE.'view/header.php';
    }
    
    public function buildMenu()
    {
    	include_once PATH_BASE.'view/menu.php';
    }
    
    
 	public function buildBody()
    {
    	
    	//Recupero parametri per action destinazione
    	if(!isset($_GET[CONTROLLER]))
    	{
    		$controller = WELCOME;
    	}
    	else
    	{
    		$controller = $_GET[CONTROLLER];
    	}
    	
    	if(!isset($_GET[ACTION]))
    	{
    		$action = DEFAULTACTION;
    	}
    	else
    	{
    		$action = $_GET[ACTION];
    	}
    	
    	
    	
    	
    	if(!isset($_SESSION[USER_SESSION]) 
    	   && 
    	   !supercontroller::verifyLoginCookie()
    	   && 
    	   ($action !='login'&& $controller !='login'))
    	{
			$controller = WELCOME;
			$action = 'toLogin';
    	}
	    	
    	try
    	{
	    	if(is_file(PATH_BASE.'/controller/'.$controller.'.php'))
    		{
    			
    			include PATH_BASE.'/controller/'.$controller.'.php';
    			$controllerClass= new ReflectionClass($controller);
    			
    			
 				$methodController = $controllerClass->getMethod($action); 
 				$controllerObj = $controllerClass->newInstanceArgs();
 				

 				$this->bodyPage = $methodController->invoke($controllerObj,Array());
 
 				
    			include PATH_BASE.'view/center.php';
    		}
    	}
    	catch(Exception $e)
    	{
    		throw new Exception(PREFIX_ERR.ERR_INVOKE_METHOD_CONTROLLER.' '.$e->getMessage());
    	}
    }
    
    public function buildFooter()
    {
    	include_once PATH_BASE.'view/footer.php';
    }
    

    
    public function getConnection()
    {
    	return $this->connection;
    }
    
    public function closeConnection()
    {
    	$this->connection->closeConnection();
    }
    
    
    public function addErrorMsg($msgError)
    {
    	$this->error[count($this->error)] = $msgError;
    }
    
    public function cleanError()
    {
    	$this->error = array();
    }
    
    public function addInfoMsg($msgInfo)
    {
    	$this->info[count($this->info)] = $msgInfo;
    }
    
    public function cleanInfo()
    {
    	$this->info = array();
    }
}

?>
